<template>
	<z-paging ref="paging" @query="queryList" :refresherEnabled="false" :loadingMoreEnabled="false"
		:auto="false" :hideEmptyView="true">
		<view slot="top">
			<z-nav-bar backState="1000">创建订单</z-nav-bar>
		</view>
		
		<view class="bg-white u-p-30" @click="handleSelectAddress">
			<template v-if="defaultAddress == null" >
				<view class="u-flex" style="line-height: 80rpx;">
					<view class="u-flex-1">
						<u-icon name="map-fill" size="20" color="#FFB143"></u-icon>
					</view>
					<view class="u-flex-9">
						<view class="u-font-32 text-bold">请新建收货地址</view>
					</view>
					<view class="u-flex-1 u-flex u-flex-end">
						<view style="opacity: 0.5;">
							<u-icon name="arrow-right" size="20"></u-icon>
						</view>
					</view>
				</view>
			</template>
			<template v-else>
				<view class="u-flex" >
					<view class="u-flex-1">
						<u-icon name="map-fill" size="20" color="#FFB143"></u-icon>
					</view>
					<view class="u-flex-9" >
						<view class="u-line-3">
							<text>{{orderHeader.province}}</text>
							<text class="u-p-l-10">{{orderHeader.city}}</text>
							<text class="u-p-l-10">{{orderHeader.area}}</text>
							<text class="u-p-l-10">{{orderHeader.address}}</text>
						</view>
						<view class="u-p-t-10" style="opacity: 0.5;">
							<text>{{orderHeader.contacts}}</text>
							<text class="u-p-l-30">{{orderHeader.contactNumber}}</text>
						</view>
					</view>
					<view class="u-flex-1 u-flex u-flex-end">
						<view style="opacity: 0.5;">
							<u-icon name="arrow-right" size="20"></u-icon>
						</view>
					</view>
				</view>
			</template>
		</view>
		
		<view class="u-m-t-30 u-p-30 bg-white solid-bottom">
			<view>
				<text class="u-font-32 text-bold">已选择商品</text>
			</view>
			<view class="u-flex u-m-t-30" v-for="(sku, index) in orderHeader.skuDetails" :key="index">
				<view class="u-flex-4">
					<image :src="sku.coverImage" style="width: 200rpx; height: 200rpx;border-radius: 30rpx;"></image>
				</view>
				<view class="u-flex-8">
					<view>{{sku.skuShortName}}</view>
					<view class="u-m-t-10">
						<text>¥</text>
						<text class="u-font-32 u-m-l-10">{{sku.sellPrice | formatMoneyToYuanFilter}}</text>
					</view>
					<view class="u-m-t-10  u-m-r-10 u-flex u-flex-wrap" >
						<view v-for="(spec, index1) in sku.specs" :key="spec.id">
							<text>{{spec.specValueName}}</text>
							<text v-if="index1 < sku.specs.length - 1">，</text>		
						</view>
						<view v-for="(gift, index2) in orderHeader.giftDetails" :key="gift.id">
							<text>，</text>
							<text>{{gift.giftName}}</text>
						</view>
					</view>
					<view class="u-flex u-flex-end u-m-t-10">
						<u-number-box v-model="sku.buyCount"></u-number-box>
					</view>
				</view>
			</view>
		</view>
		
		<!-- <view class=" u-p-30 bg-white" v-if="orderHeader.giftDetails.length > 0">
			<view>
				<text class="u-font-32 text-bold">已选择礼品</text>
			</view>
			<view class="u-flex u-m-t-30" v-for="(gift, index) in orderHeader.giftDetails">
				<view class="u-flex-4">
					<image :src="gift.coverImage" style="width: 200rpx; height: 200rpx;border-radius: 30rpx;"></image>
				</view>
				<view class="u-flex-8">
					<view>{{gift.giftName}}</view>
					<view class="u-m-t-10">
						<text>数量:</text>
						<text class="u-m-l-20">x</text>
						<text class="u-font-32 u-m-l-10">{{gift.count}}</text>
					</view>
				</view>
			</view>
		</view> -->
		
		<view class="u-m-t-30 u-flex u-p-30 bg-white" @click="handleCoupon">
			<view class="u-flex-3">
				<text>优惠券</text>
			</view>
			<view class="u-flex-8 u-text-right" >
				<template v-if="selectedCoupon">
					<text class="text-bold text-orange">-</text>
					<text class="u-m-l-10 text-orange">¥</text>
					<text class="text-orange">{{selectedCoupon.discountAmount | formatMoneyToYuanFilter}}</text>
				</template>
				<template v-else>
					<text style="opacity: 0.5;">暂无优惠券可用</text>
				</template>
			</view>
			
			<view class="u-flex-1 u-flex u-flex-end">
				<view style="opacity: 0.5;">
					<u-icon name="arrow-right" size="20"></u-icon>
				</view>
			</view>
		</view>
		
		<view class="bg-white u-p-30 u-m-t-30">
			<view class="u-flex">
				<view class="u-flex-1">买家留言</view>
				<view class="u-flex-3 text-right">
					<!-- <u-input :border="false" placeholder="买家留言" v-model="orderHeader.remark" type="text" inputAlign="left"></u-input> -->
					<u-input v-model="orderHeader.remark" border="none" clearable placeholder="买家留言" inputAlign="right"></u-input>
				</view>
			</view>
		</view>
		
		<!-- 支付方式 -->
		<view v-if="payChannels.length > 0" class="u-m-t-30 bg-white u-p-30">
			<u-radio-group placement="column" v-model="orderHeader.payChannelId">
				<view v-for="(payChannel, index) in payChannels" :class="{'u-m-b-30': index < payChannels.length - 1}" class="u-flex">
					<view class="u-flex-10 u-flex">
						<view class="u-m-r-10">
							<u-icon size="24" name="weixin-circle-fill" v-if="payChannel.key == payChannelEnum.wxApplet" color="#09bb07"></u-icon>
							<u-icon size="24" name="red-packet-fill" v-if="payChannel.key == payChannelEnum.wallet" color="#FFB143"></u-icon>
						</view>
						<view>
							<text class="u-font-32">{{payChannel.value}}</text>
							<!-- 钱包的场合，显示钱包金额 -->
							<template v-if="payChannel.key == payChannelEnum.wallet">
								<text class="u-m-l-30">余额:</text>
								<text class="u-m-l-10 u-m-r-10">{{userInfo.shopUserInfo.cashBalance | formatMoneyToYuanFilter}}</text>
								<text>元</text>
							</template>
						</view>
					</view>
					<view class="u-flex-1 u-flex u-flex-end">
						<u-radio :key="payChannel.key" :name="payChannel.key" activeColor="#FFB143"></u-radio>
					</view>
				</view>
			</u-radio-group>
		</view>
		
		<!-- <view class=" bg-white u-p-30">
			<view class="u-flex">
				<u-checkbox-group
					v-model="checkboxValue1"
					placement="column">
						<u-checkbox activeColor="#FFB143" label="通用钱包">
						</u-checkbox>
				</u-checkbox-group>
				<view>
					<text class="u-m-l-30">余额:</text>
					<text class="u-m-l-10 u-m-r-10">{{userInfo.shopUserInfo.cashBalance | formatMoneyToYuanFilter}}</text>
					<text>元</text>
				</view>
			</view>
			
			<view class="u-p-t-30 u-flex">
				<u-icon name="info-circle-fill" color="#FF0000"></u-icon>
				<text class="text-red u-m-l-10" >注意事项: 勾选通用钱包，优先扣除通用钱包余额</text> 
			</view>
		</view> -->
		
		
		<CouponSelect ref="couponDialog" :sourceOrderPrice="sourceOrderPrice" @selectedCouponCompleted="handleSelectedCouponChange"></CouponSelect>
		
		<view slot="bottom">
			<view class="u-p-30 u-flex bg-white">
				<view class="u-flex-7 u-flex">
					<view>
						<text>共</text>
						<text>{{orderHeader.skuDetails.length}}</text>
						<text>件</text>
					</view>
					<view class="u-m-l-20">
						合计:
					</view>
					<view class="u-font-40 u-m-l-20">
						<text>¥</text>
						<text>{{totalOrderPrice | formatMoneyToYuanFilter}}</text>
					</view>
				</view>
				<view class="u-flex-5 u-flex u-flex-end">
					<u-button text="确认付款" shape="circle" :customStyle="{'backgroundColor':'#FFB143', 'color': '#FFFFFF'}" @click="handleSubmit"></u-button>
				</view>
			</view>
		</view>
	</z-paging>
</template>

<script>
	import {jumpTypeEnum, payChannelEnum, orderTypeEnum} from '@/common/const.js'
	import {defaultAddress} from '@/api/address.js'
	import CouponSelect from '@/pages_one/components/coupon/select.vue'
	import {mapGetters} from 'vuex'
	import {create, pay} from '@/api/order.js'

	
	export default{
		data(){
			return{
				orderTypeEnum,
				payChannelEnum,
				defaultAddress: null,
				orderHeader:{
					payChannelId:'',
					skuDetails:[]
				},
				number:1,
				couponList:[],
				showCoupon:false,
				selectedCoupon: null,
				
				payChannels:[],
				checkboxValue1:''
			}
		},
		watch:{
			defaultAddress(e){
				this.orderHeader.province = e.province
				this.orderHeader.city = e.city
				this.orderHeader.area = e.area
				this.orderHeader.address = e.address
				this.orderHeader.contacts = e.contacts
				this.orderHeader.contactNumber = e.contactNumber			
			},
		},
		onLoad(e) {
			this.orderHeader = JSON.parse(decodeURIComponent(e.orderHeader)) 
			this.init()
			console.log(this.orderHeader)
		},
		components:{
			CouponSelect
		},
		computed:{
			...mapGetters(['payChannel', 'userInfo', 'platform']),
			
			/**
			 * 原始订单总金额
			 */
			sourceOrderPrice(){
				let totalOrderPrice = 0
				// 获取订单详情总金额
				this.orderHeader.skuDetails.forEach(sku=>{
					totalOrderPrice += sku.buyCount * sku.sellPrice
				})
				return totalOrderPrice
			},
			
			/**
			 * 订单总金额
			 */
			totalOrderPrice(){
				let result = this.sourceOrderPrice
				
				// 计算优惠券金额
				if(this.selectedCoupon){
					result -= this.selectedCoupon.discountAmount
				}
				return result
			}
		},
		methods:{
			
			/**
			 * 初始化
			 */
			init(){
				this.orderHeader.platform = this.platform
				if(this.payChannel){
					this.payChannels = JSON.parse(this.payChannel)
				}
				
				// 默认选择支付方式
				// #ifdef MP-WEIXIN || H5
				this.orderHeader.payChannelId = payChannelEnum.wxApplet
				// #endif
				this.reload()
			},
			
			/**
			 * 重新加载
			 */
			reload(){
				setTimeout(()=>{
					// 重新加载
					this.$refs.paging.reload()
				},100)
			},
			
			/**
			 * 选择收货地址
			 */
			handleSelectAddress(){
				this.jumpUtil.jumpTo(jumpTypeEnum.navigate, `/pages_one/address/index?route=order`, true)
			},
			
			/**
			 * 检索数据
			 */
			queryList(){
				// 获取默认地址
				defaultAddress().then(res=>{
					this.defaultAddress = res.data
				})
				
				// 获取优惠券
				this.$refs.couponDialog.init()
				this.$refs.paging.complete([]);
			},
			
			/**
			 * 创建订单
			 */
			handleSubmit(){
				let msg = this.checkData()
				if(msg != ''){
					this.$u.toast(msg)
					return
				}
				
				// let data = JSON.parse(JSON.stringify(this.orderHeader))
				// // 原商品金额
				// data.sourceOrderPrice = this.sourceOrderPrice
				// // 优惠后商品金额
				// data.orderPrice = this.totalOrderPrice
				// // 钱包抵扣金额
				// data.walletPrice = 0
				// // 转换sku规格
				// data.skuDetails.forEach(sku=>{
				// 	sku.skuInfo = JSON.stringify(sku.specs)
				// })
				// // 设置优惠券
				// data.coupons = []
				// if(this.selectedCoupon){
				// 	// 优惠金额
				// 	data.couponPrice = this.selectedCoupon.discountAmount
				// 	data.coupons.push(this.selectedCoupon)
				// } else {
				// 	data.couponPrice = 0
				// }
				
				let data = {
					province: this.orderHeader.province,
					address: this.orderHeader.address,
					area: this.orderHeader.area,
					city: this.orderHeader.city,
					contactNumber: this.orderHeader.contactNumber,
					contacts: this.orderHeader.contacts,
					payChannelId: this.orderHeader.payChannelId,
					platform: this.orderHeader.platform,
					walletPrice:0,
					sourceOrderPrice:this.sourceOrderPrice,
					orderPrice:this.totalOrderPrice,
					orderType: orderTypeEnum.sku,	// 商品订单
					coupons:[],
					skuDetails:[],
					giftDetails:[]
				}
				// 获取sku
				this.orderHeader.skuDetails.forEach(sku=>{
					//sku.skuInfo = JSON.stringify(sku.specs)
					data.skuDetails.push({
						skuId: sku.id,
						spuId:sku.spuId,
						spuTitle: sku.spuTitle,
						bannerImages: sku.bannerImages,
						skuInfo: JSON.stringify(sku.specs),
						buyCount: sku.buyCount
					})
				})
				
				// 获取礼品
				this.orderHeader.giftDetails.forEach(gift=>{
					data.giftDetails.push({
						giftId: gift.giftId,
						bannerImages: gift.bannerImages,
						coverImage: gift.coverImage,
						detailImages: gift.detailImages,
						count: gift.count
					})
				})
				
				// 获取优惠券
				if(this.selectedCoupon){
					data.couponPrice = this.selectedCoupon.discountAmount
					data.coupons.push({
						id: this.selectedCoupon.shopUserCouponId,
						couponId: this.selectedCoupon.id
					})
				} else {
					data.couponPrice = 0
				}
				
				// #ifdef MP-WEIXIN
				// 获取openId
				this.$store.dispatch("getOpenId", {isSave: false}).then(res=>{
					const openId = JSON.parse(res.data).openid
					// 创建订单
					create(data).then(res=>{
						let data = res.data
						let params = {
							orderId: data.id,
							totalPoint: data.totalPoint,
							totalFirstProfit: data.totalFirstProfit,
							totalSecondProfit: data.totalSecondProfit
						}
						pay({
							id: params.orderId,
							openId: openId,
							orderPrice: data.orderPrice
						}).then(res=>{
							this.wechatPay(res.data,params)
						})
						//
					})
				})
				// #endif
				
				// #ifdef H5
				console.log(data)
				// 创建订单
				create(data).then(res=>{
					let data = res.data
					let params = {
						orderId: data.id,
						totalPoint: data.totalPoint,
						totalFirstProfit: data.totalFirstProfit,
						totalSecondProfit: data.totalSecondProfit
					}
					this.jumpUtil.jumpTo(jumpTypeEnum.redirect, `/pages_one/order/finish?params=${encodeURIComponent(JSON.stringify(params))}`, true)
				})
				// #endif
				
			},
			
			/**
			 * 
			 */
			wechatPay(payParams, params){
				let that = this
				uni.requestPayment({
					provider: 'wxpay', // 服务提提供商
					timeStamp: payParams.timeStamp, // 时间戳
					nonceStr: payParams.nonceStr, // 随机字符串
					package: payParams.package,
					signType: payParams.signType, // 签名算法
					paySign: payParams.sign, // 签名
					success: function (res) {
						console.log('支付成功',res);
						//that.clearCustomShoppingCart()
						// 业务逻辑。。。
						that.jumpUtil.jumpTo(jumpTypeEnum.redirect, `/pages_one/order/finish?params=${encodeURIComponent(JSON.stringify(params))}`, true)
					},
					fail: function (err) {
						console.log('支付失败',err);
						that.jumpUtil.jumpTo(jumpTypeEnum.redirect, `/pages_one/order/detail?orderId=${params.orderId}`, true)
					}
				});
			},
			
			/**
			 * 检查数据
			 */
			checkData(){
				// 判断是否有默认地址
				if(this.defaultAddress == null){
					return '请选择收货地址'
				}
				
				if(this.orderHeader.payChannelId == null || 
					 this.orderHeader.payChannelId == ''){
					return '请选择支付方式'
				}
				
				return ''
			},
			
			/**
			 * 选择优惠券
			 */
			handleCoupon(){
				// 没有优惠券的场合
				this.$refs.couponDialog.show()
			},
			
			/**
			 * 选择优惠券后
			 */
			handleSelectedCouponChange(coupon){
				this.selectedCoupon = coupon
			}
		}
	}
</script>

<style>
</style>